<template>
  <!-- 筛选区 -->
  <div class="sub-filter">
    <div class="item" v-for="item in list" :key="item.id">
      <div class="head">{{ item.name }}：</div>
      <div class="body">
         <a
          href="javascript:;"
          @click="getAttr(item, undefined,undefined)"
          :class="{ active: item.activeName === undefined }"
        >
          全部
        </a>
        <a href="javascript:;"
        v-for="item2 in item.properties"
         :key="item2.id"
          :class="{active: item.activeName === item2.name}"
          @click="getAttr(item,item2.name,item2.id)">
          {{ item2.name }}
        </a>
      </div>
    </div>
  </div>
</template>

<script>
import { useRoute } from 'vue-router'
import { inject, computed, toRef, reactive, watch } from 'vue'
export default {
  name: 'SubFilter',
  setup () {
    const route = useRoute()
    const subData = inject('subData')
    // 解决路由切换后 品牌不重置的问题
    watch(() => route.params.id, () => {
      brands.activeName = undefined
    })
    const sortParams = inject('sortParams')
    // console.log(subData)
    // console.log(subData.value)
    const brands = reactive({ id: null, name: '品牌', properties: subData.value.brands }) // 不是响应时数据的话 没办法实时更新
    const list = computed(() => {
      return [
        brands,
        ...subData.value.saleProperties
      ]
    }
    )
    // console.log(list.value)
    const attrs = toRef(sortParams, 'attrs')
    const brandId = toRef(sortParams, 'brandId')
    const getAttr = (theItem, theName, theId) => {
      theItem.activeName = theName
      if (theItem.name === '品牌') {
        brandId.value = theId
      } else {
        const index = attrs.value.findIndex(item => item.groupName === theItem.name)
        if (index === -1) {
          attrs.value.push({
            groupName: theItem.name,
            propertyName: theName
          })
        } else {
          attrs.value[index].propertyName = theName
        }
        // console.log(attrs.value)
      }
      // 判断 item.propertyName 这个值是否存在 undefined跟null会被过滤
      attrs.value = attrs.value.filter(item => item.propertyName)
      // console.log(theItem)
      // console.log(theItem.activeName)
      // console.log(attrs.value)
      // console.log(brandId.value)
      // console.log(sortParams)
    }
    return {
      list, getAttr
    }
  }
}
</script>

<style scoped lang='less'>
  // 筛选区
  .sub-filter {
    background: #fff;
    padding: 25px;
    .item {
      display: flex;
      line-height: 40px;
      .head {
        width: 80px;
        color: #999;
      }
      .body {
        flex: 1;
        a {
          margin-right: 36px;
          transition: all .3s;
          display: inline-block;
          &.active,
          &:hover {
            color: @xtxColor;
          }
        }
      }
    }
  }
</style>
